package com.kzj.common.interceptor;

import com.kzj.common.MyUserPhoneThreadLocal;
import com.kzj.common.constant.GlobalConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
@Slf4j
public class MyLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("session Id : "+request.getSession().getId());
        String userPhone = (String)request.getSession().getAttribute("userPhone");
        if(userPhone==null)
        {
            log.warn("用户未登录");
            response.setCharacterEncoding(GlobalConstant.CHARSET_UTF_8);
            response.setStatus(401);
            response.getWriter().write("请先登录账号");
            return false;
        }
        MyUserPhoneThreadLocal.setUserPhone(userPhone);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
